import * as Utils from '../utils'

function restStart(restCallName) {
	return {
		type: `${restCallName}_START`,
		restCallName,
		callStage: 'REST_START',
	}
}

function restSuccess(restCallName, skipToJson=false) {
	return response => ({
		type: `${restCallName}_SUCCESS`,
		restCallName,
		skipToJson,
		response,
		callStage: 'REST_SUCCESS',
	})
}

function restFailed(restCallName) {
	return error => ({
		type: `${restCallName}_FAILED`,
		restCallName,
		response: error,
		callStage: 'REST_FAILED',
	})
}

export function restClearAction(restCallName) {
	return {
		type: `${restCallName}_CLEAR`,
		restCallName,
		callStage: 'REST_START',
	}
}

export function restCallAction(restCallName, restUrl, requestMethod='GET', requestBody = null, skipToJson = false) {
	let config = {
		mode: 'cors',
		method: requestMethod,
		headers: {
			Accept: 'application/json',
			'content-type': 'application/json',
		},
	}

	Object.assign(config, !!requestBody ? { body: JSON.stringify(requestBody) } : {})

	return dispatch => {
		dispatch(restStart(restCallName))
		Utils.restCall(
			restUrl,
			config,
			restSuccess(restCallName, skipToJson),
			restFailed(restCallName),
			skipToJson
		)(dispatch)
	}
}